package xyz.magicjson.core.config;

import lombok.extern.slf4j.Slf4j;
import xyz.magicjson.core.adapter.ProtocolAdapterManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ESB自动配置类，用于自动装配ESB相关组件。
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ESBProperties.class)
@ConditionalOnProperty(prefix = "easy-esb", name = "enabled", havingValue = "true", matchIfMissing = true)
@ComponentScan(basePackages = {"xyz.magicjson.core"})
public class ESBAutoConfiguration {

    private final ESBProperties properties;

    public ESBAutoConfiguration(ESBProperties properties) {
        this.properties = properties;
        log.info("初始化ESB自动配置");
    }

    /**
     * 创建ESB线程池
     *
     * @return 线程池执行器
     */
    @Bean
    @ConditionalOnMissingBean(name = "esbTaskExecutor")
    public Executor esbTaskExecutor() {
        ESBProperties.Core.ThreadPool threadPoolConfig = properties.getCore().getThreadPool();
        
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolConfig.getCoreSize());
        executor.setMaxPoolSize(threadPoolConfig.getMaxSize());
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        executor.setThreadNamePrefix(threadPoolConfig.getNamePrefix());
        executor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
        
        // 拒绝策略：使用调用者所在的线程来运行任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        log.info("ESB线程池创建成功，核心线程数: {}, 最大线程数: {}", 
                threadPoolConfig.getCoreSize(), 
                threadPoolConfig.getMaxSize());
                
        return executor;
    }
    
    /**
     * 创建协议适配器管理器
     *
     * @return 协议适配器管理器
     */
    @Bean
    @ConditionalOnMissingBean
    public ProtocolAdapterManager protocolAdapterManager() {
        return new ProtocolAdapterManager();
    }
} 